<?php

//UMA new
namespace App\Services;

use App\Models\Nikkei;
use GuzzleHttp\Client;
use Illuminate\Support\Str;
use Carbon\Carbon;

class NikkeiService
{
    public function getNikkeiDatabaseData()
    {
        return Nikkei::whereDate('date', now()->subDay())->doesntExist();
        //return Nikkei::ByDate($date)->first();
    }

    public function getNikkeiData($date)
    {
        $url = config('services.nikkei.url');
        $client = new Client();
        $datas = [];
        $i = 1;
        while(empty($datas)) {
            if($i > 10) {
                return [];
            }

            $response = $client->request('GET', $url, ['query' => [
                'api_key' => config('services.nikkei.api_key'),
                'start_date' => $date,
                'end_date' => $date
            ]]);
            $res = json_decode($response->getBody()->getContents(), true);
            if(!empty($res['dataset_data']['data'])) {
                $datas = $res;
                break;
            }
            $i ++;
            $date = Carbon::parse($date)->subDay()->toDateString();
        }

        $columns = $datas['dataset_data']['column_names'];
        $datas = $datas['dataset_data']['data'];
        $keys = array_map(function($item){return Str::slug($item, '_');}, $columns);
        $datas = array_combine($keys, $datas[0]);
        $nikkie = Nikkei::create($datas);
        if($nikkie) {
            return true;
        }
        return false;
    }
}
